// 一个用于描述 flyLine 属性 的数据源
export default class CurvesSource {

    constructor(options) {
        /**
         * 开始点位置经纬度表示
         */
        this.startPos = options.startPos

        /**
         * 结束点位置经纬度表示
         */
        this.endPos = options.endPos

        this.controlRatio = options.controlRatio

        /**
         * 线段中点位置
         */
        this.centerPos = this.linearInterpolation(this.startPos, this.endPos, 0.5)

        /**
         * 控制点位置
         */
        this.controlPos = this.getControlPoint(this.startPos, this.endPos, this.centerPos, this.controlRatio)

        /**
         * 保存上一个结束点位置 初始则为 开始点
         */
        this.lastEndPos = this.startPos

        /**
         * 计数器 用于分段
         */
        this.times = 0;

        /**
         * 曲线 数组
         */
        this.lineCoords = []

        /**
         * 箭头相关
         */
        this.arrowImage = new Image()
        this.arrowImage.src = 'arrow.png'
        this.arrowLoad = false
        this.arrowImage.onload = () => {
            this.arrowLoad = true
        }

    }

    reset(){
        this.times = 0
        this.lineCoords = []
        this.lastEndPos = this.startPos
    }

    getControlPoint(startPos, endPos, centerPos, ratio) {
        let xDiff = endPos[0] - startPos[0]
        let addX = startPos[0] + xDiff
        let addY = startPos[1]
        let controlX, controlY
        controlX = addX
        controlY = addY
        let controlPos = [controlX, controlY]
        // this real control pos  
        return this.linearInterpolation(centerPos, controlPos, ratio)
    }

    getRenderState() {
        return {
            times: this.times,
            lineCoords: this.lineCoords,
            startPos: this.startPos,
            centerPos: this.centerPos,
            endPos: this.endPos,
            lastEndPos: this.lastEndPos,
            arrowImage: this.arrowImage,
            arrowLoad: this.arrowLoad,
            controlPos: this.controlPos
        }
    }

    setRenderState(options) {
        for (let i in options) {
            this[i] = options[i]
        }
    }

    // 线性插值 函数 ... 此处的计算 只处理  二维  带x ,y 的 向量
    linearInterpolation(startPos, endPos, t) {
        let a = this.constantMultiVector2(1 - t, startPos)
        let b = this.constantMultiVector2(t, endPos)
        return this.vector2Add(a, b)
    }

    // 常数乘以二维向量数组 的函数
    constantMultiVector2(constant, vector2) {
        return [constant * vector2[0], constant * vector2[1]];
    }


    vector2Add(a, b) {
        return [a[0] + b[0], a[1] + b[1]]
    }

    // 求贝塞尔曲线上的点  通过公式 求得点
    bezierSquareCalc(startPos, center, endPos, t) {
        let a = this.constantMultiVector2(Math.pow((1 - t), 2), startPos)
        let b = this.constantMultiVector2((2 * t * (1 - t)), center)
        let c = this.constantMultiVector2(Math.pow(t, 2), endPos) // => []
        return this.vector2Add(this.vector2Add(a, b), c)
    }

}